package org.kiwi.job.web.controller;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.kiwi.job.component.RedisCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * @email jack.liu.19910921@gmail.com
 * Created by jack on 17/2/21.
 */
@RestController
@RequestMapping("/redis")
public class RedisController extends BaseController {

    @Autowired
    private RedisCacheManager cacheManager;

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public void delete(String key, HttpServletResponse response) {
        logger.info("手动清理Redis缓存,key={}", key);
        if (StringUtils.isBlank(key)) {
            writerToJson("手动清理Redis缓存时key不可为空！", response);
        } else {
            cacheManager.delete(key);
            writerToJson("手动清理Redis缓存成功! key = " + key, response);
        }
    }

    @RequestMapping(value = "/query", method = {RequestMethod.POST, RequestMethod.GET})
    public void query(String key, HttpServletResponse response) {
        logger.info("手动查询Redis缓存,key={}", key);
        if (StringUtils.isBlank(key)) {
            writerToJson("手动查询Redis缓存值时key不可为空！", response);
        } else {
            Object obj = cacheManager.get(key);
            StringBuilder builder = new StringBuilder("查询Redis缓存值成功！");
            builder.append("\n key=").append(key);
            builder.append("\n value=").append(JSONObject.toJSONString(obj));
            writerToJson(builder.toString(), response);
        }
    }
}
